package TaskServer;

import java.io.IOException;
import java.net.*;

import Node.Node;
import Node.NodeDescriptor;
import Task.Task;

public class NodeTaskServer implements NodeTaskService, Runnable{
	protected Node 	theNode;
	protected int 	port;
	protected int 	datagramBufferSize;
	
	public NodeTaskServer(Node aNode)
	{
		super();
		theNode = aNode;
		port 	= NodeDescriptor.getInstance().getPort();
		datagramBufferSize = NodeDescriptor.getInstance().getBufferSize();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		// Get the current configurations
		try {
			// Initializing the UDP Socket and wait for a new UDP.
			DatagramSocket theSocketComm = new DatagramSocket(port);
			System.out.println(">> IProxyServer: Server's Up @ Port " + port);
			
			while(true)
			{
				// Initializing an UDP Package for receiving Requests
				byte[] buffer = new byte[datagramBufferSize];
				DatagramPacket receivedPacket = new DatagramPacket(buffer, this.datagramBufferSize);
				
				theSocketComm.receive(receivedPacket);
				
				System.out.println(">> IProxyServer: Received new UDP Packet From " + 
						receivedPacket.getAddress() + 
						":" + 
						receivedPacket.getPort() +
						". Detaching new Servant");
				
				// Spawn a Servant Thread
				NodeTaskServant servant = new NodeTaskServant(this, receivedPacket);
				new Thread(servant).start();
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
		}
	}
	
	public void submitTask(Task t)
	{
		theNode.submitTask(t);
	}
	
}
